<template>
    <section>
      <ul class="template-banner-list">
        <li class="banner-item" v-for="(banner,bIndex) in bannerList" :key="bIndex" v-if="banner.deleted=='UN_DELETED'">
          <a-popconfirm title="确定删除吗？" @confirm="onItemClose(bIndex)" @cancel="banner.visible = false" okText="确定" cancelText="取消">
            <a class="banner-close"><a-icon type="close-circle" /></a>
          </a-popconfirm>
          <div class="form-wrapper">
            <div class="form-row">
              <div class="form-item__label">轮播广告</div>
              <div class="form-item__content">
                <span>排序:</span>
                <a-input-number size="small" style="width:50px" v-model="banner.sort" :min="1" @change="onSortChange"></a-input-number>
              </div>
            </div>
            <div class="form-row">
              <div class="form-item__content">
                <a-upload :showUploadList="false" :action="uploadAction" :beforeUpload="beforeUpload" @change="handleChange">
                  <div @click="onUpClick(bIndex)" class="uploadbox">
                    <img v-if="banner.imageUrl" :src="banner.imageUrl" class="banner-image"  />
                    <a-icon v-else type="cloud-upload" style="font-size:50px;color:#999"></a-icon>
                    <p class="default_tips">建议图片尺寸644*260像素，JPG、PNG格式，小于100KB</p>
                  </div>
                </a-upload>
              </div>
            </div>
            <div class="form-row">
              <div class="form-item__label">图片标题</div>
              <div class="form-item__content">
                <a-input v-model="banner.title" placeholder="(选填)"></a-input>
              </div>
            </div>
            <div class="form-row">
              <div class="form-item__label">跳转链接</div>
              <div class="form-item__content">
                <a-input-group compact style="width:420px;">
                  <a-select v-model="banner.linkType" @change="onLinkChange(banner,bIndex)"
                            placeholder="跳转类型" style="width:100px;">
                    <a-select-option :value="1">商品</a-select-option>
                    <a-select-option :value="2">自定义</a-select-option>
                  </a-select>
                  <a-input v-model="banner.linkText" readOnly v-if="banner.linkType === 1" @click.stop="handleSelect(banner,bIndex)" style="width: 320px" placeholder="跳转到的页面" />
                  <a-input v-model="banner.linkUrl" v-else style="width: 320px" placeholder="跳转到的页面" />
                </a-input-group>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div>
        <a class="banner-add" @click="onItemAdd">+添加轮播图片</a><span class="default_tips">(最多可填充10个轮播图)</span>
      </div>
      <a-modal top="2vh" title="跳转链接" v-model="dialogVisible" :footer="null" width="800px" :maskClosable="false" @cancel="handleClose">
        <select-goods @result="emitSave" :selected-key="dialogKey" v-if="dialogVisible"></select-goods>
      </a-modal>
    </section>
</template>

<script>
import SelectGoods from '../../../components/SelectGoods/index'
export default {
    name: "Banner",
    props:{
      banners:{
        type:Array,
        default:()=>{return []}
      },
      templateId:{
        type:Number,
        default: 0
      }
    },
    components:{SelectGoods},
    data(){
        return{
          bannerList:[],
          template:{
            id:null,
            sort:1,
            title:'',
            imageUrl:'',
            linkUrl:'',
            bookId:null,
            linkType:2,
            linkText:'',
            visible:false,
            deleted:'UN_DELETED',
          },
          uploadIndex:-1,
          uploadAction:this.UPLOAD_URL,
          dialogVisible:false,
          dialogKey: null
        }
    },
    watch:{
      bannerList:{
        handler (value,oldValue) {
          this.autoUpdate();
        },
        immediate:true,
        deep:true
      }
    },
    methods: {
      onItemClose(index){
        this.bannerList[index].visible = false;
        if(this.bannerList[index].id != null){
          this.bannerList[index].deleted = 'DELETED';
        }else {
          this.bannerList.splice(index, 1)
        }
      },
      onItemAdd(){
        if(this.bannerList.length>9){
          this.$message.alert("最多可填充10个轮播图");
          return;
        }
        let newBanner = this.baseUtil.modelCopy(this.template);
        let list = this.bannerList.filter(m=>m.deleted=='UN_DELETED');
        let maxSort = list.length>0?list[list.length-1].sort : 0;
        newBanner.sort = maxSort+1;
        this.bannerList.push(newBanner)
      },
      handleSelect(banner,index){
        if(banner.linkType === 1){
          this.uploadIndex = index
          this.dialogVisible = true
        }
      },
      handleClose(){
        this.dialogVisible = false
        this.uploadIndex = -1;
      },
      onLinkChange(banner,index){
        switch (banner.linkType) {
          case 1:
            this.uploadIndex = index;
            this.dialogVisible = true;
            break;
          case 2:
            banner.linkUrl = '';
            banner.linkText = '';
            break;
          default:
            banner.linkType = 2;
            break;
        }
      },
      emitSave(book){
        console.log('title====>',book)
        let editBanner =  this.bannerList[this.uploadIndex];
        this.dialogKey = null
        if(book!=null){
          this.dialogKey = book.id
          if(this.baseUtil.isBlank(editBanner.imageUrl)) editBanner.imageUrl = book.mainImage;
          editBanner.goodsId = book.id;
          editBanner.linkText = book.name;
        }
        this.dialogVisible = false;
      },
      onSortChange(){
        this.$nextTick(()=>{
          this.bannerList.sort((a,b)=>{ return a.sort - b.sort});
        })
      },
      onUpClick(index){
        console.log('upload---->',index)
        this.uploadIndex = index;
      },
      beforeUpload(file, fileList){
        this.loading = true
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isGif = file.type === 'image/gif';
        if (!isJPG && !isPNG && !isGif) {
          this.$message.error('图片格式错误,请检查后重新上传!');
          this.loading = false;
          return false;
        }
        const isLt500KB = file.size / 1024 / 500
        if (!isLt500KB) {
          this.$message.error('图片大小不合适,请上传小于500KB的图片!');
          this.loading = false;
          return false;
        }
        return true;
      },
      handleChange({file, fileList}) {
        console.log('---change>', file, fileList)
        if(file.status === 'error'){
          this.loading = false;
          return;
        }
        else if(file.status === 'done') {
          // 根据服务端返回数据筛选上传成功的文件
          if (file.response) {
            this.bannerList[this.uploadIndex].imageUrl = file.response.data;
            this.uploadIndex = -1;
            console.log('-----ok>', this.bannerList)
          }
          this.loading = false;
        }
      },
      autoUpdate(){
        console.log('----auto-->',this.bannerList)
        this.$emit("update:banners",this.bannerList)
      },
    },
    mounted(){
      let bannerList = this.banners || [];
      if(bannerList.length > 0){
        this.bannerList = bannerList;
      }else{
        this.bannerList = bannerList;
        console.log("==length>>",bannerList)
        this.onItemAdd();
      }
    }
  }
</script>
<style scoped>
  .form-wrapper{
    display: block;
  }
  .form-row{
    display: flex;
    line-height: 36px;
    margin-bottom:10px;
  }
  .form-row .form-item__label{
    flex-grow: 0;
    width:80px;
    font-size:14px;
    font-weight: bolder;
    color:#666;
  }
  .form-row .form-item__content{
    flex-grow: 1;
    text-align: left;
  }
  .uploadbox {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    width:500px;
    height:201px;
    line-height: 100px;
  }
  .uploadbox:hover {
    border-color: #409EFF;
  }
  .template-banner-list,.template-banner-list li{ list-style:none; margin:0;padding:0;}
  .template-banner-list{
    width:500px;
  }
  .banner-item{
    position: relative;
  }
  .banner-close{
    position: absolute;
    z-index: 1001;
    right:0px;
    top:0px;
    cursor: pointer;
    font-size: 16px;
    color:#555;
  }
  .banner-close:hover{
    color:#333;
  }
  .banner-image {
    width: 500px;
    height: 200px;
    display: block;
  }
  .banner-add{
    cursor: pointer;
    font-size:13px;
    font-weight: bolder;
    color:#37BCA0;
  }
</style>
